# -*- coding: utf-8 -*-
from google.appengine.api import urlfetch
from google.appengine.ext import db
import urllib

# klucz aby dzialalo zdalnie na http://ii-project-x.appspot.com/
def getAPIKey():
    return 'ABQIAAAAN3sESunn_GamP139h7V90hSgaLOYCPX5We9JrzjnJbjPyREHlRR2okAMGX2vbYDcCAy1tS6qWFgeXg'

def getStringForCords(getpt):
    return ('Coords: ' + str(getpt))

def getMapDiv(canvasName='map_canvas'):
       return '''<div id="%s" style="width: 600px; height: 500px"></div>''' % canvasName

def getMapAPIScript():
    return '''<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=%s"></script>''' % getAPIKey()

    return '''
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
    '''

def getMapForCords(getpt,canvasName='map_canvas'):

    return '''
    <script type="text/javascript">

    if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("%s"));
    var point = new GLatLng(%f,%f);
    map.addOverlay(new GMarker(point));
    map.setCenter(point, 13);
    }
    </script>
    ''' % (canvasName, getpt.lat, getpt.lon)

def getMapForMultipleCords(getpts, markerDetails, canvasName='map_canvas'):

    if not len(getpts):
        return '' # FIXME: powinno tak na prawdę rzucić wyjątkiem
    
    return '''
    <script type="text/javascript">
    
    if (GBrowserIsCompatible()) {

    var map = new GMap2(document.getElementById("%s"));

    map.setCenter(new GLatLng(%f, %f), 7);

    var polyline = new GPolyline([
    %s
    ], "#ff0000", 10);
     map.addOverlay(polyline);
     %s;
     }
     </script>
    

    ''' % (canvasName, # nazwa div'a z canvasem mapy
    getpts[0].lat, getpts[0].lon, # pierwszy punkt
    ",\n".join([ "new GLatLng(%f,%f)" % (g.lat, g.lon) for g in getpts ]), # koordynaty kolejnych punktów, wstawiane jako elementy do tablicy w JS
    # a tutaj generujemy dla każdego punktu kod JS dodający 1) marker na mapie 2) event handlery dla każdego punktu
    "\n".join([ '''
    var marker%d = new GMarker(new GLatLng(%f,%f));
    map.addOverlay(marker%d);
    GEvent.addListener( marker%d, "click", function(pos){ marker%d.openInfoWindowHtml("%s"); });
    GEvent.addListener( marker%d, "mouseover", function(pos){ marker%d.openInfoWindow("%s"); });
    GEvent.addListener( marker%d, "mouseout", function(pos){ marker%d.closeInfoWindow(); });
    ''' % (i, g.lat, g.lon,
           i,
           i,i,markerDetails[i]['infobox'],
           i,i,markerDetails[i]['infobox'],
           i,i
          ) for (i,g) in enumerate(getpts) ]))

def getGeoCoords(address):
    if address.startswith('Coords: '): # 'Coords: -11.0,2.0'
        (lat,long) = map( int, address.split(':')[1].split(','))
        return db.GeoPt(lat,long)
        
    url = "http://maps.google.com/maps/geo?q=%s&output=csv&oe=utf8&sensor=false&key=%s" % (urllib.quote(address),getAPIKey())
    result = urlfetch.fetch(url)
    if result.status_code == 200:
        
        # pola: 2,3 w split()
        # przekazujemy w tej samej kolejnosci w jakiej wyciagnelismy

        (lat,long) = result.content.split(',')[2:4]
        
        return db.GeoPt(lat,long)

